<template>
  <NoData
    v-if="noDataFlag"
    :no-data-pic="require('assets/exam/no-data.png')"
  >
    暂无数据
  </NoData>
  <div
    v-else
    v-show="!loading"
    class="page"
  >
    <QuestionHeaderH5
      :question="curQuestion"
      :index="currentSlide"
      :qlength="question.QuestionList.length"
      @feedbackCorrection="feedbackCorrection"
    />
    <!-- <ExercisesHeader
      :question="curQuestion"
      :total-number="questionList.length"
    /> -->
    <div class="content">
      <!-- <template v-if="!isOutLimit"> -->
      <CooperateMainTitle
        v-if="curQuestion.QuestionId !== 0 && curQuestion.QuestionTypeId === 5"
        :option-list="curQuestion.OptionList"
        :precondition="curQuestion.Precondition"
      />
      <SyntheticalMainTitle
        v-if="curQuestion.QuestionId !== 0
          && (curQuestion.QuestionTypeId === 7 || curQuestion.QuestionTypeId === 9
          || curQuestion.QuestionTypeId === 6)"
        :main-question-content="curQuestion.MainQuestionContent"
      />
      <!-- </template> -->
      <component
        :is="renderMain"
        v-if="questionList.length"
        :question="curQuestion"
        :should-show-answer="showAnswer"
        :swiper-index="currentSlide"
        :style="{ opacity }"
        class="question-main"
        @nextSwiper="onNextSwiper"
      />
      <div
        v-show="showAnswerBtn"
        class="show-ans-btn"
        @click="onShowAnsClick"
      >
        确定
      </div>
    </div>
    <QuestionFooterH5
      :question-info="curQuestion"
      :index="currentSlide"
      :qlength="questionList.length"
      :show-answer="false"
      @goTestCard="onGoTestCard"
      @goNext="swipeLeft"
      @goPrev="swipeRight"
    />
    <!-- <ExercisesFooter
      :question="curQuestion"
      :index="currentSlide"
      :qlength="questionList.length"
      @goNext="swipeLeft"
      @goPrev="swipeRight"
      @feedbackCorrection="feedbackCorrection"
    /> -->
  </div>
</template>
<script lang="ts">
// import Vue from 'vue'
import { SET_QUESTIONS } from '@/store/mutations'
import mixins from 'vue-typed-mixins'
import testSubmit, { MappedState } from '@/mixins/testSubmit'
export default mixins(testSubmit).extend({
  components: {
    Choose: () => import('components/Exam/Choose.vue'),
    NoData: () => import('components/Class/NoData.vue'),
    FillBlanks: () => import('components/Exam/FillBlanksQuestion.vue'),
    Subjective: () => import('components/Exam/SubjectiveQuestion.vue'),
    // ExercisesHeader: () => import('components/Exam/ExercisesHeader.vue'),
    QuestionHeaderH5: () => import('components/Exam/QuestionHeaderH5.vue'),
    // ExercisesFooter: () => import('components/Exam/ExercisesFooter.vue'),
    QuestionFooterH5: () => import('components/Exam/QuestionFooterH5.vue'),
    CooperateMainTitle: () => import('components/Exam/CooperateMainTitle.vue'),
    SyntheticalMainTitle: () => import('components/Exam/SyntheticalMainTitle.vue'),
  },
  props: {
    // totalNumber: {
    //   type: Number,
    //   default: 0,
    // },
  },
  data () {
    return {
      collectIcon: require('assets/exam/collect.png'),
      collectedIcon: require('assets/exam/collected.png'),
      noDataFlag: false,
      // questionList: [] as any[],
      currentSlide: 0,
      tempCurrentSlide: 0,
      loading: false,
      opacity: 1,
      showAnswerObj: {} as any,
    }
  },
  computed: {
    // ...mapState(['questionList']) as MappedState,
    questionList (): any[] {
      return this.question.QuestionList
      // return this.$store.state.question.QuestionList
    },
    curQuestion (): any {
      return this.questionList[this.currentSlide || 0] || {}
    },
    isRadio (): boolean {
      let isRadio = [1, 3, 6, 10].includes(this.curQuestion.QuestionTypeId)
      if (!isRadio && (this.curQuestion.QuestionTypeId === 7 ||
      this.curQuestion.QuestionTypeId === 11)) {
        isRadio = (this.curQuestion.OptionList as any[]).reduce((prevCount: number, opt) => {
          return prevCount + (opt.IsAnswer ? 1 : 0)
        }, 0) === 1
      }
      return isRadio
    },
    showAnswer (): boolean {
      return (this.isRadio && this.curQuestion.UserAnswer.length > 0) ||
      (!this.isRadio && this.showAnswerObj[this.curQuestion.QuestionId]) ||
      this.curQuestion.QuestionTypeId === 5
    },
    showAnswerBtn (): boolean {
      return !this.isRadio && !this.showAnswerObj[this.curQuestion.QuestionId] &&
      this.curQuestion.QuestionTypeId !== 5 && this.curQuestion.QuestionTypeId !== 9
    },
    renderMain (): string {
      // if (this.isOutLimit) {
      //   if (AppInfo.isApp) {
      //     AppInfo.callMethod('reLogin', '', true).then((userData: any) => {
      //       this.$store.commit(SET_USER_INFO, userData)
      //     })
      //     return ''
      //   }
      //   return 'TestTryEnd'
      // }
      // if (this.curQuestion.QuestionId === 0) {
      //   return 'QuestionDesc'
      // }
      if (this.curQuestion.QuestionTypeId === 8) {
        return 'FillBlanks'
      }
      if (this.curQuestion.QuestionTypeId === 5 || this.curQuestion.QuestionTypeId === 9) {
        return 'Subjective'
      }
      return 'Choose'
    },
  },
  activated () {
    if (window.questionIndex !== -1) {
      const toShowSlide = window.questionIndex || 0
      this.tempCurrentSlide = toShowSlide
      this.currentSlide = toShowSlide
      if (window.questionIndex) {
        delete window.questionIndex
      }
      setTimeout(() => {
        window.scrollTo(0, 0)
      })
    }
  },
  created () {
    this.fetchData()
    window.submitTestResult = this.submitResult.bind(this, false, false)
  },
  beforeDestroy () {
    window.submitTestResult = null
  },
  methods: {
    onBeforeLeave () {
      return this.submitResult(false, false)
    },
    fetchData () {
      this.loading = true
      // const { PaperId, Type, CourseId, ShowType } = this.$route.query
      this.$axios({
        url: 'ChapterPractice/DetailWithAnalysis',
        data: {
          ...this.$route.query,
          QuestionType: 0,
          doAgain: 1,
        },
        method: 'get',
      }).then(res => {
        this.loading = false
        if (res.QuestionTypeList.length === 0) {
          this.noDataFlag = true
        } else {
          this.noDataFlag = false
          const questionList: any[] = []
          let Sequence = 1;
          (res.QuestionTypeList as any[]).forEach(typeList => {
            const { QuestionList, ...oth } = typeList
            QuestionList.forEach((question: any) => {
              questionList.push({ ...question, ...oth, Sequence })
              Sequence++
            })
          })
          console.log(questionList)
          this.$store.commit(SET_QUESTIONS, { QuestionList: questionList })
          // this.$set(this.$data, 'questionList', questionList)
          // this.$store.commit(SET_QUESTIONS, { ...res })
          // if (!AppInfo.isApp) {
          // const questionList = (res.QuestionList as any[])
          //   .filter(question => question.QuestionId !== 0)
          // res.QuestionList = questionList
          // }
          // this.$store.commit(SET_QUESTIONS, res)
          // this.$set(this.$data, 'question', res)
          // this.reInit()
        }
      })
    },
    onShowAnsClick () {
      this.$set(this.$data.showAnswerObj, this.curQuestion.QuestionId, true)
    },
    onNextSwiper () {
      console.log('onNextSwiper')
      // this.swipeLeft()
    },
    // 下一题
    swipeLeft (e?: any) {
      // if (this.isOutLimit) {
      //   return
      // }
      if (this.tempCurrentSlide < this.questionList.length - 1) {
        this.opacity = 0
        this.tempCurrentSlide++
        setTimeout(() => {
          this.currentSlide++
          this.scrollTop()
          this.opacity = 1
        }, 300)
      }
    },
    // 上一题
    swipeRight (e?: any) {
      // if (this.isOutLimit && this.currentSlide !==
      // this.$store.state.instInfo.TryQuestionCount - (this.question.RightCount || 0)) {
      //   return
      // }
      if (this.tempCurrentSlide > 0) {
        this.opacity = 0
        this.tempCurrentSlide--
        setTimeout(() => {
          this.currentSlide--
          this.scrollTop(false)
          this.opacity = 1
        }, 300)
      }
    },
    scrollTop (toNext = true) {
      this.$nextTick(() => {
        if (this.whetherScrollTop(toNext)) {
          // window.scrollTo(0, 0)
          this.$el.scrollTo(0, 0)
          // const appEl = document.getElementById('app') as HTMLDivElement
          // appEl.scrollTo(0, 0)
        }
      })
    },
    whetherScrollTop (toNext: boolean) {
      if (this.curQuestion.QuestionTypeId !== 6 && this.curQuestion.QuestionTypeId !== 7) {
        return true
      }
      if (toNext && !this.curQuestion.IsSameQuestion) {
        return true
      }
      if (!toNext && !this.questionList[this.currentSlide + 1].IsSameQuestion) {
        return true
      }
      return false
    },

    // 点击跳转试题纠错页面
    feedbackCorrection () {
      window.questionIndex = -1
      this.$router.push({
        name: 'questionCorrective',
        query: {
          questionId: this.curQuestion.QuestionId,
          questionTypeDesc: this.curQuestion.QuestionTypeName,
        },
      })
    },

    onGoTestCard () {
      window.questionIndex = -1
      const { fromApp, ...othQuery } = this.$route.query
      this.$router.push({ name: 'examCard',
        query: {
          ...othQuery,
          showAnswer: '1',
          hideSubmit: '1',
        },
      })
    },
  },
})
</script>
<style lang="scss" scoped>
.page {
  padding-top: $examHeaderInH5;
  // height: 100%;
  background: #fff;
  // padding: $exerciseHeader 0 $examFooterInH5;
  padding: $examHeaderInH5 0 $examFooterInH5;
  // display: flex;
  // flex-direction: column;
  // overflow: hidden;
}
.content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  &::after {
    // 解决ios卡顿问题
    position: absolute;
    left: -1;
    top: 0;
    content: "";
    width: 1px;
    min-height: calc(100% + 1px);
  }
}
.show-ans-btn {
  width: 538px;
  height: 86px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #fff;
  background: $primary-web;
  margin: 0 auto;
  position: relative;
  top: -30px;
}
</style>
